// 物料组库
import React, {Component} from 'react';
import {connect} from 'react-redux';
import actions from '../../store/actions/materialGroup';
import {Tree} from 'antd';
import Header from './Header';
import RightInfo from './RightInfo';

import 'animate.css';
import './MaterialGroup.scss';

const {TreeNode} = Tree;

class MaterialGroup extends Component {
  state = {
    selectTitle: '',
    spinning: false
  };
  // 点击选择
  onSelect = async (selectedKeys, info) => {
    if (info.selected === true) {
      console.log(selectedKeys);
      const id = selectedKeys.toString().split(',')[0];
      await this.setState(prevState => {
        return {
          spinning: !prevState.spinning,
          selectTitle: info.selectedNodes[0].props.title
        };
      });
      await this.props.SELECT_KEY(selectedKeys);
      await this.props.GET_MAMARTERIAL_GROUP_INFO(id);
      await this.setState(prevState => {
        return {
          spinning: !prevState.spinning
        };
      });
    } else {
      this.props.SELECT_KEY('');
      this.setState({
        selectTitle: ''
      });
    }
  };
  // 自己定义的渲染tree函数
  myRender = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.cate_title} key={[item.cate_code, item.id]}>
            {this.myRender(item.children)}
          </TreeNode>
        );
      } else {
        return (<TreeNode title={item.cate_title} key={[item.cate_code, item.id]} isLeaf/>);
      }
    });
  };

  // 获取数据 初始化调用 actions中的函数
  async getData() {
    const {INIT_DATA} = this.props;
    INIT_DATA();
  }

  componentDidMount() {
    this.getData();
  }

  componentWillUnmount() {
    this.props.SELECT_KEY('');
  }

  render() {
    const {data, infoData, selectKey} = this.props;
    const {spinning} = this.state;
    return (
      <div className='materialBox animated slideInDown'>
        <Header infoData={infoData}/>
        <div className='materialBoxk'>
          <div className='treeBox'>
            <Tree
              accordion
              multiple={false}
              showLine
              blockNode
              onSelect={this.onSelect}
            >
              {this.myRender(data)}
            </Tree>
          </div>

          <div className='materialBox__content'>
            <RightInfo infoData={infoData} selectKey={selectKey} spinning={spinning}></RightInfo>
          </div>

        </div>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    data: state.materialGroup.data,
    selectKey: state.materialGroup.selectKey,
    infoData: state.materialGroup.infoData
  };
};

export default connect(mapStateToProps, actions)(MaterialGroup);
